package com.ruoyi.system.service.impl;

import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import com.paypal.http.HttpResponse;
import com.paypal.orders.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Orders;
import com.ruoyi.system.domain.PaypalConfig;
import com.ruoyi.system.mapper.OrdersMapper;
import com.ruoyi.system.service.IOrdersService;
import com.ruoyi.system.service.IPaypalConfigService;
import com.ruoyi.system.service.IPaypalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * PayPal支付Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-13
 */
@Service
public class PaypalServiceImpl implements IPaypalService {

    private static final Logger log = LoggerFactory.getLogger(PaypalServiceImpl.class);

    @Autowired
    private IPaypalConfigService paypalConfigService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 获取 PayPal HTTP 客户端
     */
    private PayPalHttpClient getPayPalClient() {
        PaypalConfig config = paypalConfigService.selectPaypalConfig();
        if (config == null) {
            throw new RuntimeException("未找到可用的PayPal配置");
        }

        PayPalEnvironment environment;
        if ("0".equals(config.getSandboxMode())) {
            // 沙箱环境
            environment = new PayPalEnvironment.Sandbox(config.getClientId(), config.getClientSecret());
        } else {
            // 生产环境
            environment = new PayPalEnvironment.Live(config.getClientId(), config.getClientSecret());
        }

        return new PayPalHttpClient(environment);
    }

    @Override
    public AjaxResult createPayment(String orderId) {
        try {
            // 获取订单信息
            Orders order = ordersMapper.selectOrdersByOrderNo(orderId);
            if (order == null) {
                return AjaxResult.error("订单不存在");
            }

            // 检查订单状态，避免重复支付
            if (order.getOrderStatus() != null && order.getOrderStatus() == 1) {
                return AjaxResult.error("订单已支付，请勿重复支付");
            }

            // 获取PayPal配置
            PaypalConfig config = paypalConfigService.selectPaypalConfig();
            if (config == null) {
                return AjaxResult.error("未找到可用的PayPal配置");
            }

            // 创建PayPal订单
            OrderRequest orderRequest = new OrderRequest();
            orderRequest.checkoutPaymentIntent("CAPTURE");

            ApplicationContext applicationContext = new ApplicationContext()
                    .brandName("smartAI")
                    .landingPage("BILLING")
                    .cancelUrl(config.getWebhookUrl() + "/cancel")
                    .returnUrl(config.getWebhookUrl() + "/success")
                    .userAction("PAY_NOW");
            orderRequest.applicationContext(applicationContext);

            List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<>();
            PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()
                    .referenceId(order.getOrderNo())
                    .description("订单: " + order.getOrderNo())
                    .amountWithBreakdown(new AmountWithBreakdown()
                            .currencyCode("USD")
                            .value(order.getTotalAmount().toString()));

            purchaseUnitRequests.add(purchaseUnitRequest);
            orderRequest.purchaseUnits(purchaseUnitRequests);

            OrdersCreateRequest request = new OrdersCreateRequest().requestBody(orderRequest);

            PayPalHttpClient client = getPayPalClient();
            HttpResponse<Order> response = client.execute(request);
            Order paypalOrder = response.result();

            String approveUrl = "";
            for (LinkDescription link : paypalOrder.links()) {
                if ("approve".equals(link.rel())) {
                    approveUrl = link.href();
                    break;
                }
            }

            if (StringUtils.isEmpty(approveUrl)) {
                return AjaxResult.error("PayPal支付链接创建失败");
            }

            // 更新订单PayPal支付ID
            Orders updateOrder = new Orders();
            updateOrder.setId(order.getId());
            updateOrder.setPaymentMethod("PayPal");
            updateOrder.setPaypalPaymentId(paypalOrder.id());
            ordersService.updateOrders(updateOrder);

            return AjaxResult.success("创建支付成功",
                    new PaymentResult(paypalOrder.id(), approveUrl));
        } catch (Exception e) {
            log.error("创建PayPal支付失败", e);
            return AjaxResult.error("创建PayPal支付失败: " + e.getMessage());
        }
    }

    @Override
    public AjaxResult executePayment(String payerId, String token) {
        try {
            OrdersCaptureRequest request = new OrdersCaptureRequest(token);

            PayPalHttpClient client = getPayPalClient();
            HttpResponse<Order> response = client.execute(request);
            Order capturedOrder = response.result();

            if ("COMPLETED".equals(capturedOrder.status())) {
                // 获取订单号 - 从PayPal订单中获取referenceId
                String orderNo = null;
                if (capturedOrder.purchaseUnits() != null && !capturedOrder.purchaseUnits().isEmpty()) {
                    orderNo = capturedOrder.purchaseUnits().get(0).referenceId();
                }

                if (StringUtils.isEmpty(orderNo)) {
                    // 如果无法从PayPal订单中获取referenceId，则通过paymentId查询
                    Orders orderQuery = new Orders();
                    orderQuery.setPaypalPaymentId(token);
                    List<Orders> ordersList = ordersService.selectOrdersList(orderQuery);

                    if (ordersList == null || ordersList.isEmpty()) {
                        return AjaxResult.error("PayPal支付完成，但系统中找不到对应订单");
                    }

                    Orders order = ordersList.get(0);

                    // 更新订单状态
                    Orders updateOrder = new Orders();
                    updateOrder.setId(order.getId());
                    updateOrder.setOrderStatus(1); // 1表示已支付
                    updateOrder.setPaymentTime(DateUtils.getNowDate());
                    ordersService.updateOrders(updateOrder);

                    return AjaxResult.success("支付成功");
                } else {
                    // 通过orderNo查询订单
                    Orders orderQuery = new Orders();
                    orderQuery.setOrderNo(orderNo);
                    List<Orders> ordersList = ordersService.selectOrdersList(orderQuery);

                    if (ordersList == null || ordersList.isEmpty()) {
                        return AjaxResult.error("PayPal支付完成，但系统中找不到对应订单");
                    }

                    Orders order = ordersList.get(0);

                    // 更新订单状态
                    Orders updateOrder = new Orders();
                    updateOrder.setId(order.getId());
                    updateOrder.setOrderStatus(1); // 1表示已支付
                    updateOrder.setPaymentTime(DateUtils.getNowDate());
                    ordersService.updateOrders(updateOrder);

                    return AjaxResult.success("支付成功");
                }
            } else {
                return AjaxResult.error("支付未完成，状态: " + capturedOrder.status());
            }
        } catch (Exception e) {
            log.error("执行PayPal支付失败", e);
            return AjaxResult.error("执行PayPal支付失败: " + e.getMessage());
        }
    }

    @Override
    public String handlePaypalCallback(String payerId, String token) {
        try {
            AjaxResult result = executePayment(payerId, token);
            if (result.isSuccess()) {
                return "<html><body><h1>支付成功</h1><script>window.close();</script></body></html>";
            } else {
                return "<html><body><h1>支付失败</h1><p>" + result.get("msg") + "</p></body></html>";
            }
        } catch (Exception e) {
            log.error("处理PayPal回调失败", e);
            return "<html><body><h1>支付处理发生错误</h1><p>" + e.getMessage() + "</p></body></html>";
        }
    }

    @Override
    public AjaxResult checkPaymentStatus(String paymentId) {
        try {
            OrdersGetRequest request = new OrdersGetRequest(paymentId);

            PayPalHttpClient client = getPayPalClient();
            HttpResponse<Order> response = client.execute(request);
            Order order = response.result();

            return AjaxResult.success("查询成功", order.status());
        } catch (Exception e) {
            log.error("查询PayPal支付状态失败", e);
            return AjaxResult.error("查询PayPal支付状态失败: " + e.getMessage());
        }
    }

    /**
     * 支付结果返回类
     */
    static class PaymentResult {
        private String paymentId;
        private String approveUrl;

        public PaymentResult(String paymentId, String approveUrl) {
            this.paymentId = paymentId;
            this.approveUrl = approveUrl;
        }

        public String getPaymentId() {
            return paymentId;
        }

        public void setPaymentId(String paymentId) {
            this.paymentId = paymentId;
        }

        public String getApproveUrl() {
            return approveUrl;
        }

        public void setApproveUrl(String approveUrl) {
            this.approveUrl = approveUrl;
        }
    }
} 